package com.yls.except.controller;


import com.google.gson.Gson;
import com.yls.except.po.Articles;
import com.yls.except.po.Item;
import com.yls.except.po.ReplyTextMessage;
import com.yls.except.po.ReplyTuwenMessage;
import com.yls.except.service.SystemService;
import com.yls.except.util.*;
import com.yls.except.util.exception.ExceptionHandle;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;


/**
 * 消息controller
 *
 * @author xs
 * @version 1.0
 * @time 2016-3-1 上午11:52:53
 * @Description: {}
 */
@Controller
@RequestMapping(value = "systemcontroller")
public class SystemController extends ExceptionHandle {
    @Resource(name = "systemService")
    private SystemService systemService;

    /**
     * 获取省
     *
     * @param req  客户端请求
     * @param resp 响应客户端
     */
    @RequestMapping(value = "getprvince.do")
    public void getProvince(HttpServletRequest req, HttpServletResponse resp) {
        List<Object> list = systemService.selectProvinceList();
        GeneralResult.resultList(list, resp);
    }

    /**
     * 获取市
     *
     * @param req  客户端请求
     * @param resp 响应客户端
     */
    @RequestMapping(value = "getcity.do")
    public void getCity(HttpServletRequest req, HttpServletResponse resp) {
        String json = req.getParameter("json");  //获取json字符串
        String pid = "";
        if (!StringIsempty.isallempty(json)) {
            Map<String, Object> map = GeneralResult.jsonStrToMap(json);
            if (map != null && map.size() > 0)
                pid = map.get("pid") + "";
        }
        List<Object> list = systemService.selectCityList(pid);
        GeneralResult.resultList(list, resp);
    }

    /**
     * 获取区
     *
     * @param req  客户端请求
     * @param resp 响应客户端
     */
    @RequestMapping(value = "getdistrict.do")
    public void getDistrict(HttpServletRequest req, HttpServletResponse resp) {
        List<Object> list = systemService.selectProvinceList();
        String json = req.getParameter("json");  //获取json字符串
        if (StringIsempty.isallempty(json))
            GeneralResult.general(resp, list, 20001, 0);
        else {
            Map<String, Object> map = GeneralResult.jsonStrToMap(json);
            if (map == null || map.size() <= 0)
                GeneralResult.general(resp, list, 20001, 0);
            String cid = map.get("cid") + "";
            list = systemService.selecDistrictList(cid);
            GeneralResult.resultList(list, resp);
        }
    }

    /**
     * 根据市名称获取区信息
     *
     * @param req  客户端请求
     * @param resp 响应客户端
     */
    @RequestMapping(value = "getdistrictbyname.do")
    public void getDistrictByName(HttpServletRequest req, HttpServletResponse resp) {
        List<Object> list = new ArrayList<Object>();
        String json = req.getParameter("json");  //获取json字符串
        if (StringIsempty.isallempty(json))
            GeneralResult.general(resp, list, 20001, 0);
        else {
            Map<String, Object> map = GeneralResult.jsonStrToMap(json);
            if (map == null || map.size() <= 0)
                GeneralResult.general(resp, list, 20001, 0);
            else {
                String cityname = map.get("cityname") + "";
                list = systemService.selecDistrictListByCityName(cityname);
                GeneralResult.resultList(list, resp);
            }
        }
    }

    /**
     * 添加收货地址
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "addaddress.action")
    public void addAddress(HttpServletRequest req, HttpServletResponse resp) {
        List<Object> list = new ArrayList<Object>();
        String uid = req.getAttribute("uid") + "";
        String name = req.getParameter("name");
        String phone = req.getParameter("phone");
        String pid = req.getParameter("pid");
        String cid = req.getParameter("cid");
        String did = req.getParameter("did");
        String address = req.getParameter("address");
        String postcode = req.getParameter("postcode");
        String reqip = IpAddressUitls.getIpAddr(req);
        if (StringIsempty.isallempty(uid))
            GeneralResult.general(resp, list, 10001, 0);
        else if (StringIsempty.isallempty(name) || StringIsempty.isallempty(phone) || StringIsempty.isallempty(pid) || StringIsempty.isallempty(cid) || StringIsempty.isallempty(address)
                || StringIsempty.isallempty(postcode))
            GeneralResult.general(resp, list, 20001, 0);
        else {
            int tag = systemService.insertAddress(uid, name, phone, pid, cid, did, address, postcode, reqip);
            GeneralResult.general(resp, list, tag, 1);
        }
    }

    /**
     * 获取我的收货地址
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "getmyaddress.action")
    public void getMyAddress(HttpServletRequest req, HttpServletResponse resp) {
        List<Object> list = new ArrayList<Object>();
        String uid = req.getAttribute("uid") + "";
        String page = req.getParameter("page");
        String searchname = req.getParameter("searchname");
        String count = req.getParameter("count");
        if (StringIsempty.isallempty(uid))
            GeneralResult.general(resp, list, 10001, 0);
        else {
            list = systemService.selectMyAddress(uid, page, searchname, count);
            Map<String, Object> userinfo = systemService.selectUserinfoById(uid);
            String type = "0";
            if(!StringIsempty.isNullMap(userinfo))
                type = userinfo.get("type") + "";

            if(StringIsempty.isNullList(list))
                GeneralResult.resultList(list, resp);
            else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("type", type);
                map.put("code", 20000);
                map.put("data", list);
                map.put("message", "");
                Gson gson = new Gson();
                String result = gson.toJson(map);
                GeneralResult.writeMessage(resp, result);
            }

        }
    }

    /**
     * 修改收货地址信息
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "editaddressinfo.action")
    public void editAddressInfo(HttpServletRequest req, HttpServletResponse resp) {
        List<Object> list = new ArrayList<Object>();
        String uid = req.getAttribute("uid") + "";
        String addressid = req.getParameter("addressid");
        String name = req.getParameter("name");
        String phone = req.getParameter("phone");
        String pid = req.getParameter("pid");
        String cid = req.getParameter("cid");
        String did = req.getParameter("did");
        String address = req.getParameter("address");
        String postcode = req.getParameter("postcode");
        String isdefault = req.getParameter("isdefault");
        if (StringIsempty.isallempty(uid))
            GeneralResult.general(resp, list, 10001, 0);
        else if (StringIsempty.isallempty(addressid))
            GeneralResult.general(resp, list, 20001, 0);
        else {
            int tag = systemService.updateAddressinfo(uid, addressid, name, phone, pid, cid, did, address, postcode, isdefault);
            GeneralResult.general(resp, list, tag, 1);
        }
    }

    /**
     * 删除收货地址信息
     * @param req
     * @param resp
     */
    @RequestMapping(value = "deladdress.action")
    public void delAddressInfo(HttpServletRequest req, HttpServletResponse resp){
        List<Object> list = new ArrayList<Object>();
        String uid = req.getAttribute("uid") + "";
        String addressid = req.getParameter("addressid");
        if(StringIsempty.isallempty(uid))
            GeneralResult.general(resp, list, 10001, 0);
        else if(StringIsempty.isallempty(addressid))
            GeneralResult.general(resp, list, 20001, 0);
        else {
            int tag = systemService.deleteAddressInfo(uid, addressid);
            GeneralResult.general(resp, list, tag, 1);
        }
    }

    /**
     * 获取收货地址详情
     * @param req
     * @param resp
     */
    @RequestMapping(value = "getaddressInfo.action")
    public void getAddressInfo(HttpServletRequest req, HttpServletResponse resp) {
        List<Object> list = new ArrayList<Object>();
        String uid = req.getAttribute("uid") + "";
        String addressid = req.getParameter("addressid");
        if(StringIsempty.isallempty(uid))
            GeneralResult.general(resp, list, 10001, 0);
        else if(StringIsempty.isallempty(addressid))
            GeneralResult.general(resp, list, 20001, 0);
        else {
            Map<String, Object> addressinfo = systemService.selectAddressInfoById(addressid);
            GeneralResult.generalMap(resp, addressinfo);
        }
    }

    /**
     * 获取开通vip金额
     * @param req
     * @param resp
     */
    @RequestMapping(value = "getvipmoney.do")
    public void getVIPMoney(HttpServletRequest req, HttpServletResponse resp) {
        List<Object> list = new ArrayList<Object>();
        String systemsetid = req.getParameter("setid");
        String uid = req.getAttribute("uid") + "";
        if(StringIsempty.isallempty(systemsetid))
            GeneralResult.general(resp, list, 20001, 0);
        else {
            Map<String, Object> vipmoney = systemService.selectSystemSetInfoById(systemsetid, uid);
            GeneralResult.generalMap(resp, vipmoney);
        }
    }

    @RequestMapping(value = "/wxtokenyz.do")
    public void wxyz(HttpServletRequest req, HttpServletResponse resp) {
//        String roomid = req.getParameter("roomid");
        String token = "hzblg";
        String signature = req.getParameter("signature");
        String timestamp = req.getParameter("timestamp");
        String nonce = req.getParameter("nonce");
        String echostr = req.getParameter("echostr");
        try {
            PrintWriter out = resp.getWriter();
            Map<String, Object> map = WeiXinUtils.parseXml(req);
            if (!StringIsempty.isNullMap(map)) {
                String message = messageHandler(map);
                out.print(message);
            } else {
                if (SignUtil.checkSignature(signature, timestamp, nonce, token)) {
                    out.print(echostr);
                }
            }
            out.close();
            out = null;
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private String messageHandler(Map<String, Object> map) {
        String MsgType = map.get("MsgType") + "";
        String Event = map.get("Event") + "";
        int nowtime = (int) (new Date().getTime() / 1000);
        String message = "";
        String ToUserName = map.get("ToUserName") + "";
        String FromUserName = map.get("FromUserName") + "";
        if ("event".equals(MsgType)) { //事件推送消息处理
            if ("SCAN".equals(Event)) {  //扫描带参二维码
                //回复图文消息
                String EventKey = map.get("EventKey") + "";
                Item item = new Item();
                item.setTitle("小丸忆");
                item.setDescription("点我，更多好礼等着你");
                item.setPicUrl("http://proya.oss-cn-shanghai.aliyuncs.com/images/119010966874196016.png");
                item.setUrl("http://www.bbbblg.com/except/page_home.jsp?friendopenid=" + EventKey);
                Articles articles = new Articles();
                articles.setItem(item);
                ReplyTuwenMessage replyTuwenMessage = new ReplyTuwenMessage();
                replyTuwenMessage.setFromUserName(ToUserName);
                replyTuwenMessage.setToUserName(FromUserName);
                replyTuwenMessage.setArticleCount(1);
                replyTuwenMessage.setArticles(articles);
                replyTuwenMessage.setCreateTime(nowtime + "");
                replyTuwenMessage.setMsgType("news");
                message = WeiXinUtils.tuwenMessageToXml(replyTuwenMessage);
            } else if ("subscribe".equals(Event)) {   //关注公众号事件
                String EventKey = map.get("EventKey") + "";
                String Ticket = map.get("Ticket") + "";
                if (StringIsempty.isallempty(EventKey)) { //直接关注公众号
                    ReplyTextMessage textMessage = new ReplyTextMessage();
                    textMessage.setContent("欢迎您加入公众平台");
                    textMessage.setCreateTime(nowtime + "");
                    textMessage.setFromUserName(ToUserName);
                    textMessage.setToUserName(FromUserName);
                    textMessage.setMessageType("text");
                    message = WeiXinUtils.textMessageToXml(textMessage);
                } else {  //扫描带参二维码关注
                    //回复图文消息
                    Item item = new Item();
                    item.setTitle("小丸忆");
                    item.setDescription("点我，更多好礼等着你");
                    item.setPicUrl("http://proya.oss-cn-shanghai.aliyuncs.com/images/119010966874196016.png");
                    item.setUrl("http://www.bbbblg.com/except/page_home.jsp?friendopenid=" + EventKey.replace("qrscene_", ""));
                    Articles articles = new Articles();
                    articles.setItem(item);
                    ReplyTuwenMessage replyTuwenMessage = new ReplyTuwenMessage();
                    replyTuwenMessage.setFromUserName(ToUserName);
                    replyTuwenMessage.setToUserName(FromUserName);
                    replyTuwenMessage.setArticleCount(1);
                    replyTuwenMessage.setArticles(articles);
                    replyTuwenMessage.setCreateTime(nowtime + "");
                    replyTuwenMessage.setMsgType("news");
                    message = WeiXinUtils.tuwenMessageToXml(replyTuwenMessage);
                }
            } else if ("unsubscribe".equals(Event)) { //取消关注公众号事件

            } else if ("LOCATION".equals(Event)) { //上报地理位置事件

            } else if ("CLICK".equals(Event)) { //自定义菜单啦取消息事件

            } else if ("VIEW".equals(Event)) { //点击菜单跳转链接时间

            }
        } else if("text".equals(MsgType)) {
            String Content = map.get("Content") + "";
            if("玩".equals(Content)) {
                //回复图文消息
                Item item = new Item();
                item.setTitle("爱，要大声说");
                item.setDescription("戳我，进入七夕音乐狂欢节");
                item.setPicUrl("http://proya.oss-cn-shanghai.aliyuncs.com/images/upload/20170825/716JpXn.jpg");
                item.setUrl("http://mtl.tairui88.com/ins?roomid=45&openid=" + FromUserName);
                Articles articles = new Articles();
                articles.setItem(item);
                ReplyTuwenMessage replyTuwenMessage = new ReplyTuwenMessage();
                replyTuwenMessage.setFromUserName(ToUserName);
                replyTuwenMessage.setToUserName(FromUserName);
                replyTuwenMessage.setArticleCount(1);
                replyTuwenMessage.setArticles(articles);
                replyTuwenMessage.setCreateTime(nowtime + "");
                replyTuwenMessage.setMsgType("news");
                message = WeiXinUtils.tuwenMessageToXml(replyTuwenMessage);
            }
        }
        return message;
    }
}
